# build the package
os = require 'os'
fs = require 'fs-extra'
fsp = require '../libs/fs-promises'
path = require 'path'
_ = require 'underscore'
Handlebars = require 'handlebars'
bodyParser = require 'body-parser'
package_promise = require '../libs/package_promise'

module.exports = (app, prefix, workdir) ->

  app.use bodyParser.json() # for parsing application/json
  app.use bodyParser.urlencoded({ extended: true }) # for parsing application/x-www-form-urlencoded

  app.get prefix, (req, res) ->
    #render the build page
    res.render 'build'

  app.post prefix, (req, res, next) ->

    # check parameter
    if !req.body.title || !req.body.platform
      res.render 'build', { msg: 'not enought parameters' }
      return
    # 应用沙箱
    sandbox_path = path.resolve workdir if workdir

    # 服务器URL
    serverUrl = "#{req.protocol}://#{req.hostname}:#{process.env.PORT || 3000}"
    # 应用URL
    baseUrl = "#{serverUrl}" # for this app, serverUrl is the base URL
    console.log "app #{baseUrl}"

    bundleIdentifier = req.body.bundleIdentifier || "com.yonyou.innovation"

    res.setTimeout 1000*60*6 # express默认2min
    # 1 生成临时目录
    tempProject = path.resolve os.tmpdir(), "app"
    # request each json file from server and replace local ones
    fsp.traverse_safe path.resolve(sandbox_path, 'js', 'pages'), relative: true
    .then (pages) ->
      _.chain(pages).filter (file) ->
        !file.startsWith('_') and file.endsWith('.json')
      .map (each) ->
        each = each.replace('.json', '')
      .value()
    .then (page_names) ->
      # 调用打包过程
      package_promise(bundleIdentifier, sandbox_path, baseUrl, page_names, tempProject, req, res)
    .catch (err) ->
      next(err)
